package com.lpcluster;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import java.util.Date;

/**
 * Main Android activity class for GUI
 * @author edward
 */
public class MainActivity extends Activity {

	static MainActivity singleton = null;
	private Intent powerIntent, clusterIntent;
	private long nCreateTime = new Date().getTime();

	/**
	 * Setup UI when the activity is first created.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		if (singleton != null || LPCluster.sOutput.length() > 0) return;
		singleton = this;
		clusterIntent = new Intent(this,LPCluster.class);
		clusterIntent.putExtra("nCreateTime", nCreateTime);
		startService(clusterIntent);
	}

	@Override
	public void onResume() {
		super.onResume();
		updateText();
	}

	@Override
	public void onPause() {
		super.onPause();
		if (powerIntent != null) {
			stopService(powerIntent);
			LPCluster.post("powerIntent killed");
		}
		if (clusterIntent != null) {
			stopService(clusterIntent);
			LPCluster.post("clusterIntent killed");
		}
	}

	void updateText() {
		runOnUiThread(new Runnable() {
			public void run() {
				((TextView) findViewById(R.id.label)).setText(LPCluster.sOutput.toString());
			}
		});
	}

	/**
	 * Start PowerTutor
	 */
	void start() {
		powerIntent = new Intent().setClassName("edu.umich.PowerTutor",
						"edu.umich.PowerTutor.service.UMLoggerService");
		startService(powerIntent);
	}

	/**
	 * Stop current experiment and output log file
	 * @param sFileName Log file name
	 */
	void stop(String sFileName) {
		Intent stopIntent = new Intent(powerIntent).putExtra("stop", true);
		if (sFileName != null) stopIntent.putExtra("logFile", nCreateTime + "_" + sFileName + ".log");
		startService(stopIntent);
		
		//	Start PowerTutor for next experiment
		if (sFileName != null) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException ex) {
			}
			startService(powerIntent);
		}
	}
}
